﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace GN.Pay.Utils.Security
{
    /// <summary>
    /// Md5 帮助
    /// </summary>
    public static class Md5Utils
    {
        /// <summary>
        /// 签名
        /// </summary>
        /// <param name="content">内容</param>
        /// <param name="encoding">编码</param>
        /// <returns></returns>
        public static string Sign(string content, Encoding encoding)
        {
            ExceptionUtils.CheckNotNullOrNotWhiteSpace(content, nameof(content));
            ExceptionUtils.CheckNotNull(encoding, nameof(encoding));
            StringBuilder builder = new StringBuilder();
            using (var crypto = new MD5CryptoServiceProvider())
            {
                byte[] buffer = crypto.ComputeHash(encoding.GetBytes(content));
                for (int i = 0; i < buffer.Length; i++)
                {
                    builder.Append(buffer[i].ToString("x").PadLeft(2, '0'));
                }
                return builder.ToString();
            }
        }

        /// <summary>
        /// 签名验证,默认不区分大小写
        /// </summary>
        /// <param name="content">内容</param>
        /// <param name="sign">验名</param>
        /// <param name="encoding">编码</param>
        /// <returns></returns>
        public static bool SginVerify(string content, string sign, Encoding encoding)
        {
            return (Sign(content, encoding).Equals(sign));
        }

        /// <summary>
        /// 签名验证,默认不区分大小写
        /// </summary>
        /// <param name="content">内容</param>
        /// <param name="sign">验名</param>
        /// <param name="encoding">编码</param>
        /// <returns></returns>
        public static bool SginIgnoreCaseVerify(string content, string sign, Encoding encoding)
        {
            return (Sign(content, encoding).Equals(sign, StringComparison.InvariantCultureIgnoreCase));
        }
    }
}
